﻿using System.Data;
using AutoMapper;
using System.Collections.Generic;

namespace EasyGo.Data
{
    public static class DataReaderExtensions
    {
        public static IList<T> ReadAll<T>(this IDataReader reader)
        {
            var result = Mapper.Map<IDataReader, IList<T>>(reader);
            return result;
        }

        public static T ReadSingle<T>(this IDataReader reader)
            where T : class
        {
            if (!reader.Read())
            {
                throw new DaoException("No data found");
            }

            var result = Mapper.Map<IDataReader, T>(reader);
            if (result == null)
            {
                throw new DaoException("Result was not mapped properly - mapping returned null");
            }

            if (reader.Read())
            {
                throw new DaoException("More than one record found");
            }
            return result;
        }

        public static T ReadFirst<T>(this IDataReader reader)
            where T : class
        {
            if (!reader.Read())
            {
                throw new DaoException("No data found");
            }

            var result = Mapper.Map<IDataReader, T>(reader);
            if (result == null)
            {
                throw new DaoException("Result was not mapped properly - mapping returned null");
            }
            return result;
        }


        public static T ReadFirstOrDefault<T>(this IDataReader reader)
               where T : class
        {
            if (!reader.Read())
            {
                return null;
            }

            var result = Mapper.Map<IDataReader, T>(reader);
            if (result == null)
            {
                throw new DaoException("Result was not mapped properly - mapping returned null");
            }
            return result;
        }


        public static T ReadSingleOrDefault<T>(this IDataReader reader)
               where T : class
        {
            if (!reader.Read())
            {
                return null;
            }

            var result = Mapper.Map<IDataReader, T>(reader);
            if (result == null)
            {
                throw new DaoException("Result was not mapped properly - mapping returned null");
            }

            if (reader.Read())
            {
                throw new DaoException("More than one record found");
            }
            return result;
        }
    }
}
